<template>
  <view class="coupon-center-container">
    <!-- 标题栏 -->
    <view class="header">
      <view class="back-btn" @tap="goBack">
        <text class="back-icon">←</text>
      </view>
      <text class="title">领券中心</text>
    </view>
    
    <!-- 优惠券列表 -->
    <view class="coupon-list">
      <!-- 优惠券卡片 -->
      <view class="coupon-card" v-for="(coupon, index) in allCoupons" :key="coupon.id">
        <!-- 优惠券金额部分 -->
        <view class="coupon-amount">
          <text class="currency-symbol" v-if="coupon.type === '0'">折扣券</text>
          <text class="currency-symbol" v-else>¥</text>
          <text class="amount-value">{{ coupon.type === '0' ? coupon.discountText : coupon.preferentialMoney || '0' }}</text>
          <view class="condition" v-if="coupon.triggerMoney">
            <text class="condition-text">满{{ coupon.triggerMoney }}元可用</text>
          </view>
        </view>
        <!-- 分隔线样式处理 -->
        <view class="coupon-separator">
          <view class="left-circle"></view>
          <view class="dashed-line"></view>
          <view class="right-circle"></view>
        </view>
        <!-- 优惠券信息部分 -->
        <view class="coupon-info">
          <text class="coupon-description">{{ coupon.name }}</text>
          <text class="coupon-validity">{{ coupon.validityRange }}</text>
        </view>
        <!-- 领取按钮 -->
        <view class="coupon-action">
          <button 
            class="get-coupon-btn" 
            @tap="handleCouponAction(coupon)"
            :disabled="coupon.status === 1"
          >
            {{ coupon.isAgain ? '再次领取' : '领取' }}
          </button>
        </view>
      </view>
      <view class="no-coupon" v-if="allCoupons.length === 0">
        <text class="no-coupon-text">暂无可用优惠券</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      coupons: [], // 可领取优惠券
      againCoupons: [], // 可再次领取优惠券
      loading: false
    }
  },
  computed: {
    // 合并所有优惠券
    allCoupons() {
      return [...this.coupons, ...this.againCoupons]
    },
    // 获取用户ID
    userId() {
      // 实际应用中应该从登录状态或缓存中获取
      return uni.getStorageSync('userId') || 18
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 格式化折扣为文本
    formatDiscount(discount) {
      if (!discount) return ''
      const discountMap = {
        0.1: '一折',
        0.2: '二折',
        0.3: '三折',
        0.4: '四折',
        0.5: '五折',
        0.6: '六折',
        0.7: '七折',
        0.8: '八折',
        0.9: '九折'
      }
      return discountMap[discount] || `${Math.round(discount * 10)}折`
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}.${month}.${day}`
    },
    
    // 获取可领取优惠券
    fetchCoupons() {
      this.loading = true
      uni.request({
        url: 'http://localhost:8080/cc/merchant/selectCouponList',
        method: 'GET',
        data: {
          uId: this.userId
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            // 处理优惠券数据
            this.coupons = res.data.data.map(item => ({
              id: item.id,
              name: item.name,
              type: item.type,
              discount: item.discount,
              discountText: this.formatDiscount(item.discount),
              triggerMoney: item.triggerMoney,
              preferentialMoney: item.preferentialMoney,
              validityRange: `${this.formatDate(item.expirationStart)}至${this.formatDate(item.expirationEnd)}`,
              status: item.status,
              isAgain: false
            }))
          }
        },
        fail: (err) => {
          console.error('获取优惠券列表失败:', err)
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    
    // 获取可再次领取优惠券
    fetchAgainCoupons() {
      uni.request({
        url: 'http://localhost:8080/cc/merchant/selectCouponListAgain',
        method: 'GET',
        data: {
          uId: this.userId
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            // 处理再次领取优惠券数据
            this.againCoupons = res.data.data.map(item => ({
              id: item.id,
              name: item.name,
              type: item.type,
              discount: item.discount,
              discountText: this.formatDiscount(item.discount),
              triggerMoney: item.triggerMoney,
              preferentialMoney: item.preferentialMoney,
              validityRange: `${this.formatDate(item.expirationStart)}至${this.formatDate(item.expirationEnd)}`,
              status: item.status,
              isAgain: true
            }))
          }
        },
        fail: (err) => {
          console.error('获取再次领取优惠券列表失败:', err)
        }
      })
    },
    
    // 处理优惠券操作
    handleCouponAction(coupon) {
      // 如果优惠券已结束，不执行操作
      if (coupon.status === 1) {
        return
      }
      
      uni.showLoading({
        title: coupon.isAgain ? '再次领取中...' : '领取中...'
      })
      
      // 第一步：调用consume接口
      const consumeParams = {
        name: coupon.name
      }

      //打印consumeParams
      console.log('consumeParams:', consumeParams)
      
      uni.request({
        url: 'http://localhost:8080/cc/merchant/consume',
        method: 'POST',
        data: consumeParams,
        success: (res) => {
          // 检查返回数据格式
          // 情况1：返回优惠券已领取完
          if (res.statusCode === 200 && res.data && res.data.code === 500 && res.data.msg === '该优惠券已领取完') {
            // 调用updateCouponStatus接口
            //打印coupon.name
            console.log('coupon.name:', coupon.name)

            uni.request({
              url: 'http://localhost:8080/cc/merchant/updateCouponStatus',
              method: 'GET',
              data: {
                queueName: coupon.name
              },
              success: () => {
                uni.showToast({
                  title: '该优惠券已领完',
                  icon: 'success'
                })
              },
              fail: (err) => {
                console.error('调用updateCouponStatus接口失败:', err)
                uni.showToast({
                  title: '操作失败',
                  icon: 'none'
                })
              },
              complete: () => {
                uni.hideLoading()
                // 刷新当前页面
                setTimeout(() => {
                  uni.reLaunch({
                    url: '/pages/coupon-center/coupon-center'
                  })
                }, 1000)
              }
            })
          } 
          // 情况2：返回成功
          else if (res.statusCode === 200 && res.data && res.data.code === 200 && res.data.msg === '成功' && res.data.data) {
            // 根据是否是再次领取调用不同的接口
            if (coupon.isAgain) {
              // 再次领取：调用updateUserCouponStatus接口
              uni.request({
                url: 'http://localhost:8080/cc/merchant/updateUserCouponStatus',
                method: 'GET',
                data: {
                  uId: 18, // 默认用户ID
                  cId: coupon.id
                },
                success: () => {
                  uni.showToast({
                    title: '再次领取成功',
                    icon: 'success'
                  })
                },
                fail: (err) => {
                  console.error('调用updateUserCouponStatus接口失败:', err)
                  uni.showToast({
                    title: '再次领取失败',
                    icon: 'none'
                  })
                },
                complete: () => {
                uni.hideLoading()
                // 刷新当前页面
                setTimeout(() => {
                  uni.reLaunch({
                    url: '/pages/coupon-center/coupon-center'
                  })
                }, 1000)
              }
              })
            } else {
              // 首次领取：调用insertCouponToUser接口
              uni.request({
                url: 'http://localhost:8080/cc/merchant/insertCouponToUser',
                method: 'GET',
                data: {
                  uId: 18, // 默认用户ID
                  cId: coupon.id,
                  num: 1,
                  status: 0
                },
                success: () => {
                  uni.showToast({
                    title: '领取成功',
                    icon: 'success'
                  })
                },
                fail: (err) => {
                  console.error('调用insertCouponToUser接口失败:', err)
                  uni.showToast({
                    title: '领取失败',
                    icon: 'none'
                  })
                },
                complete: () => {
                uni.hideLoading()
                // 刷新当前页面
                setTimeout(() => {
                  uni.reLaunch({
                    url: '/pages/coupon-center/coupon-center'
                  })
                }, 1000)
              }
              })
            }
          } else {
            // 其他错误情况
            uni.showToast({
              title: '操作失败',
              icon: 'none'
            })
            uni.hideLoading()
            // 刷新当前页面
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/coupon-center/coupon-center'
              })
            }, 1000)
          }
        },
        fail: (err) => {
            console.error('调用consume接口失败:', err)
            uni.showToast({
              title: '网络请求失败',
              icon: 'none'
            })
            uni.hideLoading()
            // 刷新当前页面
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/coupon-center/coupon-center'
              })
            }, 1000)
          }
      })
    }
  },
  onLoad() {
    // 页面加载时获取优惠券数据
    this.fetchCoupons()
    this.fetchAgainCoupons()
  }
}
</script>

<style scoped>
.coupon-center-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 30rpx;
}

/* 标题栏样式 */
.header {
  padding: 60rpx 0 30rpx 0;
  text-align: center;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.back-btn {
  position: absolute;
  left: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  padding: 10rpx;
  margin-top: 10px;
}

.back-icon {
  font-size: 40rpx;
  font-weight: bold;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin: auto;
}

.header-right {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  padding: 10rpx;
  display: flex;
  align-items: center;
}

.more-icon,
.filter-icon {
  font-size: 32rpx;
  margin-left: 20rpx;
}

/* 优惠券列表样式 */
.coupon-list {
  padding: 30rpx;
}

/* 优惠券卡片样式 */
.coupon-card {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  display: flex;
  position: relative;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  height: 220rpx; /* 设置固定高度 */
  margin-bottom: 30rpx; /* 增加卡片间距 */
}

/* 优惠券金额部分 */
.coupon-amount {
  background-color: #1677ff;
  color: #fff;
  padding: 30rpx 20rpx; /* 减小内边距 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-width: 160rpx;
}

.currency-symbol {
  font-size: 28rpx; /* 减小字体 */
  line-height: 1;
}

.amount-value {
  font-size: 45rpx; /* 减小字体 */
  font-weight: bold;
  line-height: 1;
}

.condition {
  margin-top: 15rpx;
}

.condition-text {
  font-size: 22rpx; /* 减小字体 */
  background-color: rgba(255, 255, 255, 0.3);
  padding: 4rpx 10rpx;
  border-radius: 10rpx;
}

/* 优惠券信息部分 */
.coupon-info {
  flex: 1;
  padding: 30rpx 20rpx; /* 减小内边距 */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.coupon-description {
  font-size: 28rpx; /* 减小字体 */
  color: #333;
  margin-bottom: 15rpx;
  font-weight: bold;
}

.coupon-validity {
  font-size: 22rpx; /* 减小字体 */
  color: #999;
}

/* 优惠券操作按钮 */
.coupon-action {
  display: flex;
  align-items: center;
  padding: 0 20rpx;
}

.get-coupon-btn {
  background-color: #1677ff;
  color: #fff;
  border: none;
  border-radius: 16rpx;
  font-size: 26rpx; /* 减小字体 */
  padding: 14rpx 28rpx;
  white-space: nowrap;
}

.get-coupon-btn:active {
  background-color: #0958d9;
}

/* 已领取状态的按钮样式 */
.get-coupon-btn[disabled] {
  background-color: #f5f5f5;
  color: #999;
}
</style>